function getImageInfo(url) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: resolve,
      fail: reject,
    })
  })
}

function createRpx2px() {
  const { windowWidth } = wx.getSystemInfoSync()
  return function(rpx) {
    return windowWidth / 750 * rpx
  }
}
const rpx2px = createRpx2px()
function canvasToTempFilePath(option, context) {
  return new Promise((resolve, reject) => {
    wx.canvasToTempFilePath({
      ...option,
      success: resolve,
      fail: reject,
    }, context)
  })
}
function saveImageToPhotosAlbum(option) {
  return new Promise((resolve, reject) => {
    wx.saveImageToPhotosAlbum({
      ...option,
      success: resolve,
      fail: reject,
    })
  })
}
function arrStr(arr) {
  let arrs = []
  arr.forEach((el,index)=>{
    if(index<4){
      arrs.push(el.name)
    }
  })
  return arrs.join(' ')
}
Component({
  properties: {
    visible: {
      type: Boolean,
      value: false,
      observer(visible) {
        if (visible && !this.beginDraw) {
          this.draw()
          this.beginDraw = true
        }
      }
    },
    userInfo: {
      type: Object,
      value: false
    }
  },
  data: {
    beginDraw: false,
    isDraw: false,
    canvasWidth: 900,
    canvasHeight: 1400,
    imageFile: '',
    responsiveScale: 1,
  },

  lifetimes: {
    ready() {
      const designWidth = 375
      const designHeight = 603 // 这是在顶部位置定义，底部无tabbar情况下的设计稿高度
      // 以iphone6为设计稿，计算相应的缩放比例
      const { windowWidth, windowHeight } = wx.getSystemInfoSync()
      const responsiveScale =
        windowHeight / ((windowWidth / designWidth) * designHeight)
      if (responsiveScale < 1) {
        this.setData({
          responsiveScale,
        })
      }
    },
  },

  methods: {
    handleClose() {
      this.triggerEvent('close')
    },
    handleSave() {
      const { imageFile } = this.data
      console.log(imageFile)
      if (imageFile) {
        saveImageToPhotosAlbum({
          filePath: imageFile,
        }).then(() => {
          wx.showToast({
            icon: 'none',
            title: '分享图片已保存至相册',
            duration: 2000,
          })
        })
      }
    },
    draw() {
      wx.showLoading()
      const { userInfo, canvasWidth, canvasHeight } = this.data
      const avatarUrl = userInfo.card.member.avatar
      const wximg = userInfo.wximg
      const avatarPromise = getImageInfo(avatarUrl)
      const backgroundPromise = getImageInfo('https://dh.yinkelai.com/images/imgbg.png')
      const backgroundPromise1 = getImageInfo('https://dh.yinkelai.com/images/imgbg1.png')
      const wximgPromise = getImageInfo(wximg)

      Promise.all([avatarPromise, backgroundPromise, backgroundPromise1, wximgPromise, userInfo.card, userInfo.type])
        .then(([avatar, background,background1,wximg,card,type]) => {
          const ctx = wx.createCanvasContext('share', this)
          const canvasW = rpx2px(canvasWidth * 2)
          const canvasH = rpx2px(canvasHeight * 2)
          const side = 120;  // 边距
          // 绘制背景
          const bgwh = 260,avatarwh = 180;// 宽高
          // ctx.drawImage(background1.path,0,0,canvasW,canvasH)

          ctx.drawImage(background.path,side/2,side/2,canvasW-side,canvasH-side/2)
          // ctx.drawImage(background1.path, 0, rpx2px(1030), canvasW, 40)
          ctx.drawImage(wximg.path,canvasW-bgwh-side,canvasH-bgwh-side,bgwh,bgwh)
          ctx.drawImage(avatar.path,canvasW-avatarwh-side,avatarwh/1.5,avatarwh,avatarwh)
          // 绘制用户名
          ctx.setFillStyle('#000')
          ctx.setFontSize(50)
          if(type==1){
            ctx.fillText(card.name, side, rpx2px(300))
            ctx.setFontSize(36)
            ctx.fillText(`${card.company} - ${card.position}`, side,rpx2px(450))
          }else{
            ctx.fillText(card.nature_name, side, rpx2px(300))
            ctx.setFontSize(36)
            ctx.fillText('达人', side,rpx2px(450))
          }
          ctx.fillText('电话：'+card.mobile,side,rpx2px(600))
          ctx.fillText('微信：'+card.wechat,side,rpx2px(750))
          const addr = card.province + card.city + card.area;
          ctx.fillText('地址：' + addr, side, rpx2px(900))
          ctx.setFontSize(50)
          if(type==1){
            ctx.fillText('产品信息', side, rpx2px(1300))
            ctx.setFontSize(36)
            ctx.fillText( (card.mark==null?'-':card.mark), side, rpx2px(1450))
          }else{
            ctx.fillText('平台信息', side, rpx2px(1300))
            ctx.setFontSize(36)
            ctx.fillText('名字：' + card.name, side, rpx2px(1450))
            ctx.fillText('ID：' + card.account, side, rpx2px(1600))
            ctx.fillText('粉丝数：' + card.fans, side, rpx2px(1750))
            ctx.fillText('领域：' + arrStr(card.domain), side, rpx2px(1900))
            ctx.fillText('详细介绍：' + (card.introduce==null?'-':card.introduce.slice(0,6)+'...'), side, rpx2px(2050))
          }
          ctx.stroke()

          ctx.draw(false, () => {
            canvasToTempFilePath({
              canvasId: 'share',
            }, this).then(({ tempFilePath }) => this.setData({ imageFile: tempFilePath }))
          })
          setTimeout(()=>{
            this.setData({ isDraw: true })
            wx.hideLoading()
          },200)
        })
        .catch(() => {
          this.setData({ beginDraw: false })
          wx.hideLoading()
        })
    }
  }
})